<template>
  <div class="alarm-data bg-background text-foreground p-6">
    <h2 class="mb-6 text-2xl font-bold">报警数据</h2>

    <div class="search-form bg-card text-card-foreground mb-6 rounded-lg p-6 shadow-md">

      <QueryForm :model="search" :formItems="formItems" @search="searchAlarms" @reset="resetSearch" />
    </div>

    <div
      class="action-buttons bg-card text-card-foreground mb-6 flex items-center justify-between rounded-lg p-4 shadow-md">
      <div class="flex space-x-2">
        <!-- <button @click="openAddDialog" class="btn btn-primary">新增</button>
        <button @click="deleteSelected" class="btn btn-destructive">
          删除
        </button> -->
        <!-- <el-button type="primary" @click="openAddDialog" style="width: 75px; height: 30px;">新增</el-button> -->
        <el-button @click="deleteSelected" style="width: 75px; height: 30px;">删除</el-button>
        <el-button @click="exportData" style="width: 75px; height: 30px;">导出</el-button>
        <!-- <button @click="openImportDialog" class="btn btn-secondary">
          导入
        </button>
        <button @click="exportData" class="btn btn-secondary">导出</button> -->
      </div>
    </div>

    <div class="data-table bg-card text-card-foreground overflow-hidden rounded-lg shadow-md">
      <div class="overflow-x-auto">
        <table class="divide-border min-w-full divide-y">
          <thead>
            <tr class="bg-muted">
              <th class="table-header w-[60px]">
                <input type="checkbox" :checked="selectAll" @change="toggleSelectAll" class="checkbox" />
              </th>
              <th class="table-header">报警编码</th>
              <th class="table-header">报警设备编码</th>
              <th class="table-header">报警设备类型</th>
              <th class="table-header">报警时间</th>
              <th class="table-header">报警类型</th>
              <th class="table-header">经度</th>
              <th class="table-header">纬度</th>
              <th class="table-header">处置状态</th>
              <th class="table-header">处置时间</th>
              <!-- <th class="table-header">操作</th> -->
            </tr>
          </thead>
          <tbody class="divide-border divide-y">
            <tr v-for="item in displayedAlarmData" :key="item.id" class="hover:bg-muted/50">
              <td class="table-cell w-[60px]">
                <input type="checkbox" v-model="item.selected" class="checkbox" />
              </td>
              <td class="table-cell">{{ item.ALARM_CODE }}</td>
              <td class="table-cell">{{ item.ALARM_EQUIP_CODE }}</td>
              <td class="table-cell">{{ item.ALARM_EQUIP_TYPE }}</td>
              <td class="table-cell">{{ formatDateTime(item.ALARM_TIME) }}</td>
              <td class="table-cell">{{ item.ALARM_TYPE }}</td>
              <td class="table-cell">{{ item.LONGITUDE }}</td>
              <td class="table-cell">{{ item.DIMENSION }}</td>
              <td class="table-cell">{{ item.STATUS }}</td>
              <td class="table-cell">
                {{ formatDateTime(item.HANDLING_TIME) }}
              </td>
              <!-- <td class="table-cell">
                <button @click="editAlarm(item)" class="btn btn-sm btn-secondary mr-2">
                  编辑
                </button>
              </td> -->
            </tr>
          </tbody>
        </table>
      </div>
    </div>


    <!--  -->
    <Pagination v-if="alarmData.length" :tableData="alarmData" @alltabledata="alltabledata" />
    <!-- Add/Edit Alarm Dialog -->
    <Teleport to="body">
      <div v-if="isAddDialogOpen"
        class="bg-background/80 fixed inset-0 flex items-center justify-center backdrop-blur-sm">
        <div class="bg-card text-card-foreground w-full max-w-md rounded-lg p-6 shadow-xl">
          <h3 class="mb-4 text-lg font-semibold">
            {{ isEditing ? '编辑报警数据' : '新增报警数据' }}
          </h3>
          <form @submit.prevent="saveAlarm">
            <div class="space-y-4">
              <div>
                <label for="modalAlarmCode" class="text-muted-foreground block text-sm font-medium">报警编码</label>
                <input id="modalAlarmCode" v-model="formData.ALARM_CODE" type="text" class="input" required />
              </div>
              <div>
                <label for="modalEquipCode" class="text-muted-foreground block text-sm font-medium">报警设备编码</label>
                <input id="modalEquipCode" v-model="formData.ALARM_EQUIP_CODE" type="text" class="input" required />
              </div>
              <div>
                <label for="modalEquipType" class="text-muted-foreground block text-sm font-medium">报警设备类型</label>
                <select id="modalEquipType" v-model="formData.ALARM_EQUIP_TYPE" class="input" required>
                  <option value="定位终端">定位终端</option>
                  <option value="电子围栏">电子围栏</option>
                  <option value="其他">其他</option>
                </select>
              </div>
              <div>
                <label for="modalAlarmTime" class="text-muted-foreground block text-sm font-medium">报警时间</label>
                <input id="modalAlarmTime" v-model="formData.ALARM_TIME" type="datetime-local" class="input" required />
              </div>
              <div>
                <label for="modalAlarmType" class="text-muted-foreground block text-sm font-medium">报警类型</label>
                <select id="modalAlarmType" v-model="formData.ALARM_TYPE" class="input" required>
                  <option value="入侵">入侵</option>
                  <option value="超速">超速</option>
                  <option value="求救">求救</option>
                  <option value="滞留">滞留</option>
                </select>
              </div>
              <!-- <div>
                <label
                  for="modalAlarmLocation"
                  class="text-muted-foreground block text-sm font-medium"
                  >报警位置</label
                >
                <input
                  id="modalAlarmLocation"
                  v-model="formData.location"
                  type="text"
                  class="input"
                  required
                />
              </div> -->
              <div>
                <label for="modalLongitude" class="text-muted-foreground block text-sm font-medium">经度</label>
                <input id="modalLongitude" v-model="formData.LONGITUDE" type="number" step="0.000001" class="input"
                  required />
              </div>
              <div>
                <label for="modalLatitude" class="text-muted-foreground block text-sm font-medium">纬度</label>
                <input id="modalLatitude" v-model="formData.DIMENSION" type="number" step="0.000001" class="input"
                  required />
              </div>

              <div>
                <label for="modalAlarmStatus" class="text-muted-foreground block text-sm font-medium">处置状态</label>
                <select id="modalAlarmStatus" v-model="formData.STATUS" class="input" required>
                  <option value="已处置">已处置</option>
                  <option value="未处置">未处置</option>
                </select>
              </div>
              <!-- <div>
                <label
                  for="modalDescription"
                  class="text-muted-foreground block text-sm font-medium"
                  >描述</label
                >
                <textarea
                  id="modalDescription"
                  v-model="formData.description"
                  class="input"
                  rows="3"
                ></textarea>
              </div>
              <div>
                <label
                  for="modalHandlingPerson"
                  class="text-muted-foreground block text-sm font-medium"
                  >处理人</label
                >
                <input
                  id="modalHandlingPerson"
                  v-model="formData.handling_person"
                  type="text"
                  class="input"
                />
              </div> -->
              <div>
                <label for="modalHandlingTime" class="text-muted-foreground block text-sm font-medium">处置时间</label>
                <input id="modalHandlingTime" v-model="formData.HANDLING_TIME" type="datetime-local" class="input" />
              </div>
              <!-- <div>
                <label
                  for="modalHandlingResult"
                  class="text-muted-foreground block text-sm font-medium"
                  >处理结果</label
                >
                <textarea
                  id="modalHandlingResult"
                  v-model="formData.handling_result"
                  class="input"
                  rows="3"
                ></textarea>
              </div> -->
            </div>
            <div class="mt-4 flex justify-end space-x-2">
              <button @click="closeAddDialog" type="button" class="btn btn-secondary">
                取消
              </button>
              <button type="submit" class="btn btn-primary">保存</button>
            </div>
          </form>
        </div>
      </div>
    </Teleport>

    <!-- Import Dialog -->
    <Teleport to="body">
      <div v-if="isImportDialogOpen"
        class="bg-background/80 fixed inset-0 flex items-center justify-center backdrop-blur-sm">
        <div class="bg-card text-card-foreground w-[400px] rounded-lg p-5 shadow-xl">
          <h3 class="mb-4 text-lg font-bold">导入报警数据</h3>
          <input type="file" @change="handleFileUpload" accept=".xlsx, .xls"
            class="text-muted-foreground file:bg-primary file:text-primary-foreground hover:file:bg-primary/80 mb-4 block w-full text-sm file:mr-4 file:rounded-full file:border-0 file:px-4 file:py-2 file:text-sm file:font-semibold" />
          <div class="flex justify-end space-x-2">
            <button @click="closeImportDialog" class="btn btn-secondary">
              取消
            </button>
            <button @click="importData" class="btn btn-primary">导入</button>
          </div>
        </div>
      </div>
    </Teleport>

    <!-- View Details Dialog -->
    <Teleport to="body">
      <div v-if="isViewDialogOpen"
        class="bg-background/80 fixed inset-0 flex items-center justify-center backdrop-blur-sm">
        <div class="bg-card text-card-foreground w-[800px] rounded-lg p-5 shadow-xl">
          <div class="mb-4 flex items-center justify-between">
            <h3 class="text-lg font-bold">查看报警数据详情</h3>
            <button @click="closeViewDialog" class="text-muted-foreground hover:text-foreground">
              <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"
                xmlns="http://www.w3.org/2000/svg">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
              </svg>
            </button>
          </div>
          <div v-if="viewingAlarm" class="grid grid-cols-2 gap-4">
            <div><strong>报警编码：</strong>{{ viewingAlarm.alarm_code }}</div>
            <div><strong>报警类型：</strong>{{ viewingAlarm.alarm_type }}</div>
            <div><strong>报警位置：</strong>{{ viewingAlarm.location }}</div>
            <div><strong>经度：</strong>{{ viewingAlarm.longitude }}</div>
            <div><strong>纬度：</strong>{{ viewingAlarm.latitude }}</div>
            <div>
              <strong>报警时间：</strong>{{ formatDateTime(viewingAlarm.alarm_time) }}
            </div>
            <div><strong>报警状态：</strong>{{ viewingAlarm.status }}</div>
            <div><strong>描述：</strong>{{ viewingAlarm.description }}</div>
            <div>
              <strong>处理人：</strong>{{ viewingAlarm.handling_person }}
            </div>
            <div>
              <strong>处理时间：</strong>{{ formatDateTime(viewingAlarm.handling_time) }}
            </div>
            <div>
              <strong>处理结果：</strong>{{ viewingAlarm.handling_result }}
            </div>
            <div class="col-span-2">
              <strong>通行抓拍：</strong>
              <img v-if="viewingAlarm.pass_img" :src="viewingAlarm.pass_img" alt="通行抓拍"
                class="mt-2 h-auto max-w-full" />
              <span v-else>无抓拍</span>
            </div>
          </div>
          <div class="mt-4 flex justify-end">
            <button @click="closeViewDialog" class="btn btn-secondary">
              关闭
            </button>
          </div>
        </div>
      </div>
    </Teleport>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { getCurrentInstance } from 'vue'
import * as XLSX from 'xlsx'

const { proxy } = getCurrentInstance()

const apiBaseUrl = computed(() => {
  return proxy.$currentUrl + '/api/alarm-data'
})

const search = ref({
  ALARM_CODE: '',
  ALARM_EQUIP_TYPE: '',
  ALARM_TYPE: '',
  STATUS: '',
})
const formItems = ref([
  {
    label: '报警编码:',
    model: 'ALARM_CODE',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '报警设备类型：',
    model: 'ALARM_EQUIP_TYPE',
    type: 'select',
    placeholder: '请输入',
    options: [
      { label: '定位终端', value: '定位终端' },
      { label: '电子围栏', value: '电子围栏' },
      { label: '其他', value: '其他' },
    ],
  },
  {
    label: '报警类型：',
    model: 'ALARM_TYPE',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '入侵', value: '入侵' },
      { label: '超速', value: '超速' },
      { label: '求救', value: '求救' },
      { label: '滞留', value: '滞留' },
    ],
  },
  {
    label: '处置状态：',
    model: 'STATUS',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '已处置', value: '已处置' },
      { label: '未处置', value: '未处置' },

    ],
  },
])
const alarmData = ref([])

const selectAll = ref(false)
const isAddDialogOpen = ref(false)
const isImportDialogOpen = ref(false)
const isEditDialogOpen = ref(false)
const isViewDialogOpen = ref(false)
const formData = ref({
  ID: null,
  ALARM_CODE: '',
  ALARM_EQUIP_CODE: '',
  ALARM_EQUIP_TYPE: '',
  ALARM_TYPE: '',
  ALARM_TIME: '',
  LONGITUDE: '',
  DIMENSION: '',
  STATUS: '',
  HANDLING_TIME: '',
})
const viewingAlarm = ref(null)
const importFile = ref(null)



const displayedAlarmData = ref([])
const alltabledata = (data) => {
  displayedAlarmData.value = data

}
const searchAlarms = async () => {
  try {
    const response = await axios.get(`${apiBaseUrl.value}/search`, {
      params: search.value,
    })
    alarmData.value = response.data.map((alarm) => ({
      ...alarm,
      selected: false,
    }))
  } catch (error) {
    console.error('搜索报警记录失败:', error)
    alert(
      '搜索报警记录失败: ' + (error.response?.data?.message || error.message),
    )
  }
}

const resetSearch = () => {
  search.value = {
    ALARM_CODE: '',
    ALARM_EQUIP_TYPE: '',
    ALARM_TYPE: '',
    STATUS: '',
  }
  searchAlarms()
}

const addNewAlarm = async () => {
  try {
    // if (formData.value.created_at) {
    //   formData.value.created_at = formatDateTimeForInput(
    //     formData.value.created_at,
    //   );
    // }
    if (formData.value.alarm_time) {
      formData.value.alarm_time = formatDateTimeForInput(
        formData.value.alarm_time,
      )
    }
    if (formData.value.handling_time) {
      formData.value.handling_time = formatDateTimeForInput(
        formData.value.handling_time,
      )
    }
    const response = await axios.post(apiBaseUrl.value, formData.value)
    alert(response.data.message || '创建报警记录成功')
    closeAddDialog()
    await searchAlarms()
  } catch (error) {
    console.error('创建报警记录失败:', error)
    alert(
      '创建报警记录失败: ' + (error.response?.data?.message || error.message),
    )
  }
}

const deleteSelected = async () => {
  const selectedIds = alarmData.value
    .filter((alarm) => alarm.selected)
    .map((alarm) => alarm.id)
  if (selectedIds.length === 0) {
    alert('请选择要删除的记录')
    return
  }
  if (confirm(`确定要删除选中的 ${selectedIds.length} 条记录吗？`)) {
    try {
      await Promise.all(
        selectedIds.map((id) => axios.delete(`${apiBaseUrl.value}/${id}`)),
      )
      alert('删除成功')
      await searchAlarms()
    } catch (error) {
      console.error('删除记录失败:', error)
      alert(
        '删除记录失败: ' + (error.response?.data?.message || error.message),
      )
    }
  }
}

const updateAlarm = async () => {
  try {
    const response = await axios.put(
      `${apiBaseUrl.value}/${formData.value.id}`,
      formData.value,
    )
    alert(response.data.message || '更新报警记录成功')
    closeAddDialog()
    await searchAlarms()
  } catch (error) {
    console.error('更新报警记录失败:', error)
    alert(
      '更新报警记录失败: ' + (error.response?.data?.message || error.message),
    )
  }
}

const exportData = () => {
  const dataToExport = alarmData.value.map(({ id, selected, ...rest }) => ({
    // ...rest,
    报警编码: rest.ALARM_CODE,
    报警设备编码: rest.ALARM_EQUIP_CODE,
    报警设备类型: rest.ALARM_EQUIP_TYPE,
    报警时间: formatDateTime(rest.ALARM_TIME),
    报警类型: rest.ALARM_TYPE,
    经度: rest.LONGITUDE,
    纬度: rest.DIMENSION,
    处置状态: rest.STATUS,
    处置时间: formatDateTime(rest.HANDLING_TIME),
  }))
  const worksheet = XLSX.utils.json_to_sheet(dataToExport)
  const workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet, '报警数据')
  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
  const data = new Blob([excelBuffer], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  })
  const link = document.createElement('a')
  link.href = window.URL.createObjectURL(data)
  link.download = '报警数据.xlsx'
  link.click()
}

const importData = async () => {
  if (!importFile.value) {
    alert('请选择要导入的文件')
    return
  }
  const formData = new FormData()
  formData.append('file', importFile.value)
  try {
    const response = await axios.post(`${apiBaseUrl.value}/import`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
    alert(response.data.message || '导入成功')
    closeImportDialog()
    await searchAlarms()
  } catch (error) {
    console.error('导入失败:', error)
    alert('导入失败: ' + (error.response?.data?.message || error.message))
  }
}

const openAddDialog = () => {
  isAddDialogOpen.value = true
  formData.value = {
    // id: null,
    // alarm_code: '',
    // alarm_type: '',
    // location: '',
    // longitude: '',
    // latitude: '',
    // alarm_time: new Date().toISOString().slice(0, 16),
    // status: '未处理',
    // description: '',
    // handling_person: '',
    // handling_time: '',
    // handling_result: '',
    ID: null,
    ALARM_CODE: '',
    ALARM_EQUIP_CODE: '',
    ALARM_EQUIP_TYPE: '',
    ALARM_TYPE: '',
    ALARM_TIME: '',
    LONGITUDE: '',
    DIMENSION: '',
    STATUS: '',
    HANDLING_TIME: '',
  }
}

const closeAddDialog = () => {
  isAddDialogOpen.value = false
}

const openImportDialog = () => {
  isImportDialogOpen.value = true
}

const closeImportDialog = () => {
  isImportDialogOpen.value = false
  importFile.value = null
}

const editAlarm = (alarm) => {
  formData.value = { ...alarm }
  // if (formData.value.created_at) {
  //   formData.value.created_at = formatDateTimeForInput(
  //     formData.value.created_at,
  //   );
  // }
  if (formData.value.ALARM_TIME) {
    formData.value.ALARM_TIME = formatDateTimeForInput(
      formData.value.ALARM_TIME,
    )
  }
  if (formData.value.HANDLING_TIME) {
    formData.value.HANDLING_TIME = formatDateTimeForInput(
      formData.value.HANDLING_TIME,
    )
  }
  isAddDialogOpen.value = true
}

const closeEditDialog = () => {
  isEditDialogOpen.value = false
}

const viewDetails = (alarm) => {
  viewingAlarm.value = { ...alarm }
  isViewDialogOpen.value = true
}

const closeViewDialog = () => {
  isViewDialogOpen.value = false
  viewingAlarm.value = null
}

const toggleSelectAll = () => {
  selectAll.value = !selectAll.value
  alarmData.value.forEach((alarm) => (alarm.selected = selectAll.value))
}

const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toLocaleString()
}

const formatDateTimeForInput = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toISOString().slice(0, 16) // 格式为 "YYYY-MM-DDTHH:mm"
}

const saveAlarm = async () => {
  if (formData.value.id) {
    await updateAlarm()
  } else {
    await addNewAlarm()
  }
}


onMounted(() => {
  searchAlarms()
})
</script>

<style scoped>
.input {
  @apply border-input bg-background placeholder:text-muted-foreground focus:ring-ring mt-1 block w-full rounded-md px-3 py-2 text-sm shadow-sm focus:outline-none focus:ring-1;
}

.btn {
  @apply rounded-md px-4 py-2 font-medium transition duration-150 ease-in-out focus:outline-none focus:ring-2 focus:ring-offset-2;
}

.btn-primary {
  @apply bg-primary text-primary-foreground hover:bg-primary/90;
}

.btn-secondary {
  @apply bg-secondary text-secondary-foreground hover:bg-secondary/80;
}

.btn-destructive {
  @apply bg-destructive text-destructive-foreground hover:bg-destructive/90;
}

.checkbox {
  @apply text-primary focus:ring-primary border-input h-4 w-4 rounded;
}

.table-header {
  @apply text-muted-foreground px-6 py-3 text-left text-xs font-medium uppercase tracking-wider;
}

.table-cell {
  @apply whitespace-nowrap px-6 py-4 text-sm;
}

.btn-pagination {
  @apply border-border relative inline-flex items-center border px-4 py-2 text-sm font-medium;
}

.btn-sm {
  @apply px-2 py-1 text-sm;
}
</style>
